import { Component, Input, Output, EventEmitter } from "@angular/core";
import { KVAny } from "../type/kv";

/**
 * checkOptions = [
 *  {
 *    title: "Doctor",
 *    checked: false,
 *    children: [
 *      { label: "Apple", value: "Apple", checked: true },
 *      { label: "Pear", value: "Pear", checked: false },
 *      { label: "Orange", value: "Orange", checked: false }
 *    ]
 *  },
 *  {
 *    title: "Nurse",
 *    checked: false,
 *   children: [
 *      { label: "Apple", value: "Apple", checked: true },
 *     { label: "Pear", value: "Pear", checked: false },
 *      { label: "Orange", value: "Orange", checked: false }
 *    ]
 *  },
 *  {
 *    title: "Teacher",
 *    checked: false,
 *    children: [
 *     { label: "Apple", value: "Apple", checked: true },
 *      { label: "Pear", value: "Pear", checked: false },
 *     { label: "Orange", value: "Orange", checked: false }
 *    ]
 *  }
 * ];
 */

@Component({
  selector: "n-checkbox-all",
  template: `
    <div
      style="border-bottom: 1px solid rgb(233, 233, 233); padding-bottom: 10px;"
    >
      <label
        nz-checkbox
        [(ngModel)]="allChecked"
        (ngModelChange)="updateAllChecked()"
        [nzIndeterminate]="indeterminate"
      >
        {{ title }}
      </label>
    </div>
    <br />
    <nz-checkbox-group
      [(ngModel)]="checkOptionsOne"
      (ngModelChange)="updateSingleChecked()"
    ></nz-checkbox-group>
  `
})
export class CheckboxAllComponent {
  @Input() title = "Check All";
  @Input() checkOptionsOne = [];
  @Output() checkOptionsOneChange = new EventEmitter<KVAny[]>();

  allChecked = false;
  indeterminate = true;

  updateAllChecked() {
    this.indeterminate = false;
    if (this.allChecked) {
      this.checkOptionsOne = this.checkOptionsOne.map(item => {
        return {
          ...item,
          checked: true
        };
      });
    } else {
      this.checkOptionsOne = this.checkOptionsOne.map(item => {
        return {
          ...item,
          checked: false
        };
      });
    }
  }

  updateSingleChecked() {
    if (this.checkOptionsOne.every(item => !item.checked)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.checkOptionsOne.every(item => item.checked)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }
  }
}
